<?php

/**
 * 公共函数
 * @package  module/func
 */

quanli_require('module/func/encryption.func.php');
quanli_require('module/base/system/itemHandler.class.php');
quanli_require('module/base/goods/quanliGoods.class.php');
quanli_require('module/base/goods/goodsBasic.class.php');

/**
 * 生成流水号
 * @param string $name 流水号名称
 * @param null|string $prefix 前缀
 * @param bool|string $is_transaction  使用事务
 * @return null|string
 * //mod by allen.qiang 20150415 解决并发时，取得相同数据的问题 start
 */

function generate_seqno($name, $prefix=null, $is_transaction = false) {
    global $G_SHOP;
    $seq_no = null;
    $seq_no_ge = null;

    if(!$is_transaction){
    //mod by allen.qiang 20150415 解决并发时，取得相同数据的问题 start
        //if ($G_SHOP->DBCA->stmt_query('UPDATE sys_seqno SET seqno = seqno + 1 WHERE name = ?', 's', $name)){
        if ($G_SHOP->DBCA->stmt_query('UPDATE sys_seqno SET seqno = LAST_INSERT_ID(seqno+1) WHERE name = ?', 's', $name)){
            //$seq_no =& $G_SHOP->DBCA->stmt_query('SELECT seqno FROM sys_seqno WHERE name = ?', 's', $name);
            $seq_no =& $G_SHOP->DBCA->stmt_query('SELECT LAST_INSERT_ID() AS seqno FROM sys_seqno WHERE name = ?', 's', $name);
            if (!is_null($seq_no)) {
                $seq_no = $seq_no[0]->seqno;
            }
        }
    //mod by allen.qiang 20150415 解决并发时，取得相同数据的问题 end
    }else{

        $G_SHOP->DBCA->beginTransaction();
        try{
            if ($G_SHOP->DBCA->stmt_query('UPDATE sys_seqno SET seqno = seqno + 1 WHERE name = ?', 's', $name)){
                $seq_no =& $G_SHOP->DBCA->stmt_query('SELECT seqno FROM sys_seqno WHERE name = ?', 's', $name);
                if (!is_null($seq_no)) {
                    $seq_no = $seq_no[0]->seqno;
                }
            }

            $G_SHOP->DBCA->commit();

        }catch (Exception $e){

            $G_SHOP->DBCA->rollBack();
            $seq_no = null;

        }

    }

    if (is_null($seq_no))
        return null;

    switch ($name) {
        case 'seqno_bill_goods':
            $seq_no_ge = date('Ymd') . str_repeat('0', 5 - strlen($seq_no)) . $seq_no;
            break;

        case 'seqno_card_no':
            $seq_no_ge = date('ymd') . str_repeat('0', 7 - strlen($seq_no)) . $seq_no;
            break;

        case 'seqno_bill':
            $seq_no_ge = date('Ymd') . str_repeat('0', 10 - strlen($seq_no)) . $seq_no;
            break;

        case 'seqno_cost':
        case 'seqno_temp':
        case 'seqno_sale':
        $seq_no_ge = date('Ymd') . str_repeat('0', 6 - strlen($seq_no)) . $seq_no;
            break;
        default:
            $seq_no_ge = $seq_no;
            break;
    }
    if (!is_null($prefix))
        $seq_no_ge = $prefix . $seq_no_ge;

    return $seq_no_ge;

}

/**
 * 获得订单编号
 * @param string $table_name 表名
 * @param null $prefix
 * @return null|string
 */
function get_bill_code($table_name, $prefix=null){
    $seq_no_ge = null;
    $seq_no = generate_seqno($table_name, $prefix);

    $seq_no_ge = substr(date('Y'),-1).date('md') . str_repeat('0', 4 - strlen($seq_no)).$seq_no.mt_rand(10,99);
    if (!is_null($prefix))
        $seq_no_ge = $prefix . $seq_no_ge;
    return $seq_no_ge;
}

/**
 * 生成UUID（唯一）
 * @return mixed
 */
function make_uuid() {
    $address = strtolower('localhost' . '/' . '127.0.0.1');
    list ( $usec, $sec ) = explode(" ", microtime());
    $time = $sec . substr($usec, 2, 3);
    $random = rand(0, 1) ? '-' : '';
    $random = $random . rand(1000, 9999) . rand(1000, 9999) . rand(1000, 9999) . rand(100, 999) . rand(100, 999);
    $uuid = strtoupper(md5($address . ':' . $time . ':' . $random));
    $uuid = substr($uuid, 0, 8) . '-' . substr($uuid, 8, 4) . '-' . substr($uuid, 12, 4) . '-' . substr($uuid, 16, 4) . '-' . substr($uuid, 20);
    $uuid = str_replace("-", "", $uuid);
    return $uuid;
}

/**
 * 生成预览页面参数
 * @return string
 */
function echo_preview_url() {
    return 'act=' . encryptD(date('mdY') . '_callpreView_' . date('iHs'));
}

/**
 * 生成发布页面参数
 * @return string
 */
function echo_publish_url() {
    return 'act=' . encryptD(date('mdY') . '_callpUblish_' . date('iHs'));
}

/**
 * require加载文件
 * @param string $file_name 文件名
 */
function quanli_require($file_name) {

    $md5_name = strtolower(md5($file_name));

    if (!defined($md5_name)) {
        define($md5_name, 1);
        require ($file_name);
    }
}

/**
 * include加载文件
 * @param string $file_name 文件名
 */
function quanli_include($file_name) {

    $md5_name = strtolower(md5($file_name));

    if (!defined($md5_name)) {
        define($md5_name, 1);
        include ($file_name);
    }
}

/**
 * 生成商品详情页链接地址
 * @param int $id 商品网购号
 * @param int $type 类型 1、PC 2、WAP
 * @return string
 */
function set_goods_link($id, $type = 1) {
    if ($type == 1) {
        return G_WEBSITE_DOMAINNAME . '/shop/goods-' . $id . '.html';
    } else {
        return G_WEBSITE_DOMAINNAME . '/wap/goods-' . $id . '.html';
    }

}

/**
 * 生成商品图片地址
 * @param string $val 商品图片地址
 * @return string
 */
function set_goods_img_link( $val ) {
    return G_IMAGE_URL . 'goods/' . $val;
}


/**
 * 把一些预定义的字符转换为 HTML 实体【已废弃】
 * @param string $str
 * @return string
 */
function convertVar($str) {

    if (!isset($str) || empty($str))
        return null;
    return htmlspecialchars(trim($str));
}

/**
 * 把一些预定义的字符转换为 HTML 实体
 * @param string $str
 * @return string
 */
function convert_var($str) {

    if (!isset($str) || empty($str))
        return '';

    $preg = '/<script[\s\S]*?<\/script>/i';
    $str = preg_replace($preg, '', $str, 3);
    if (empty($str)) {
        return '';
    }

    return htmlspecialchars(nl2br(trim($str)));

}

/**
 * 隐藏手机号码中间四位数字
 * @param int $mobile 手机号码
 * @return mixed
 */
function hide_mobile($mobile) {
    return substr_replace($mobile, '****', 3, -4);
}

function hide_email( $email ) {

    $arr = explode('@', $email);
    $arr[0] = substr_replace($arr[0], '****', 1, -1);
    return $arr[0] . '@' . $arr[1];

}

/**
 * 检测变量是否是密码
 * 密码只能是6-30位英文、数字及“_”、“-”组成
 * @author 刘道健
 * @param string $val 密码
 * @return bool
 */
function is_pwd($val) {
    return preg_match('/^[\w-]{6,30}$/', $val);
}

/**
 * 检测变量是否是密码
 * 密码是6-30位英文、数字及符号组成(因此只判断长度)
 * @author allen.qiang
 * @param string $val 密码
 * @return bool
 */
function is_pwd_A($val) {
    if(strlen($val)<6 || strlen($val)>30)
        return false;
    return true;
}

/**
 * 检测变量是否是邮件地址
 * @author 刘道健
 * @param string $val email
 * @return bool
 */
function is_email($val) {
    return preg_match('/^[\w-]+(\.[\w-]+)*\@[A-Za-z0-9]+((\.|-|_)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/', $val);
}


/**
 * 检测变量是否是手机号码
 * 手机号码必须是11位的数字，第一位数字必须为1，第二数字必须是34568中的任意一个
 * @param string $val 手机号码
 * @return bool
 */
function is_mobile($val) {
    return preg_match('/^1\d{10}$/', $val);
}


/**
 * 检测变量是否是座机号码
 * 3-4位区号，7-8位直播号码，1－4位分机号
 * @param string $val 座机号码
 * @return bool
 */
function is_phone($val) {
    return preg_match('/^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$/', $val);
}

/**
 * 检测变量是否是日期或日期+时间
 * @param $val
 * @return bool
 */
function is_date( $val ) {
    return preg_match('/^\d{4}-\d{2}-\d{2}|\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/s', $val);
}

/**
 * 读取的Excel日期，转换
 */

function excelTime($date, $time = false) {
    if(function_exists('GregorianToJD')){
        if (is_numeric( $date )) {
            $jd = GregorianToJD( 1, 1, 1970 );
            $gregorian = JDToGregorian( $jd + intval ( $date ) - 25569 );
            $date = explode( '/', $gregorian );
            $date_str = str_pad( $date [2], 4, '0', STR_PAD_LEFT )
                ."-". str_pad( $date [0], 2, '0', STR_PAD_LEFT )
                ."-". str_pad( $date [1], 2, '0', STR_PAD_LEFT )
                . ($time ? " 00:00:00" : '');
            return $date_str;
        }
    }else{
        $date=$date>25568?$date+1:25569;
        /*There was a bug if Converting date before 1-1-1970 (tstamp 0)*/
        $ofs=(70 * 365 + 17+2) * 86400;
        $date = date("Y-m-d",($date * 86400) - $ofs).($time ? " 00:00:00" : '');
    }
    return $date;
}

/**
 * 检查是否是整数
 * @param string $val 值
 * @param int $type 默认为空【1.大于0的整数 2.大于等于的整数 3.小于0的整数 4.小于等于0的整数】
 * @return bool
 */
function quanli_is_int($val, $type = 1) {

    if (ceil($val) != $val)
        return false;

    if ($type == 1 && $val <= 0)
        return false;
    else if ($type == 2 && $val < 0)
        return false;
    else if ($type == 3 && $val >= 0)
        return false;
    else if ($type == 4 && $val > 0)
        return false;

    return true;
}

/**
 * 检测变量是否是金额
 * @param string $val 金额
 * @param int $type 默认为空【1.大于0的金额 2.大于等于的金额 3.小于0的金额 4.小于等于0的金额】
 * @return bool
 */
function is_money( $val, $type = null ) {

    if (!preg_match('/^\d*(\.\d{1,2})?$/', $val))
        return false;

    if ($type == 1 && $val <= 0)
        return false;
    else if ($type == 2 && $val < 0)
        return false;
    else if ($type == 3 && $val >= 0)
        return false;
    else if ($type == 4 && $val > 0)
        return false;

    return true;

}

/**
 * 转换字符串为半角格式
 * @param string $str
 * @return null|string
 */
function to_half_angle($str) {

    if (!isset($str) || empty($str)) {
        return NULL;
    }

    $arr = array(
        //数字
        '０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4', '５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
        //大写字母
        'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E', 'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J', 'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O', 'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T', 'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y', 'Ｚ' => 'Z',
        // 小写字母
        'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd', 'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i', 'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n', 'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's', 'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x', 'ｙ' => 'y', 'ｚ' => 'z',
        //括号
        '（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[', '】' => ']', '〖' => '[', '〗' => ']', '《' => ' < ', '》' => ' > ', '｛' => ' {', '｝' => '} ',
        //其它
        '％' => '%', '＋' => ' + ', '—' => '-', '－' => '-', '～' => '-', '．' => '.', '：' => ':', '。' => '.', '，' => ',', '、' => '\\', '；' => ':', '？' => '?', '！' => '!', '…' => '-', '‖' => '|', '“' => "\"", '”' => "\"", '‘' => '`', '’' => '`', '｜' => '|', '〃' => "\"", '　' => ' '
    );

    return strtr($str, $arr);
}

/**
 * 系统错误信息
 * @param string $message
 * @return array
 */
function systemError($message = '系统错误') {
    return array('code' => 500, 'message' => $message);
}

/**
 * 后台错误返回
 * @param string $msg
 */
function backendError($msg = '参数错误') {

    global $G_SHOP;

    $G_SHOP->display_error_page($msg);

}

/**
 * 前端错误返回
 * @param string $msg
 */
function shopError($msg = '参数错误') {

    global $G_SHOP;

    $G_SHOP->display_error_page($msg);

}

/**
 * 返回json格式的数据
 * @param $msg
 * @param int $code
 * @param array $data
 */
function returnJsonData($msg, $code = 400, $data = array()) {
    die(json_encode(array('code' => $code, 'message' => $msg, 'data' => $data)));
}

function getSortNum($table_name, $sort_field = 'sortOrder') {

    global $G_SHOP;

    if (!isset($table_name) || empty($table_name)) {
        return 0;
    }

    try {

        //查询最大排序序号
        $search_sql = sprintf('SELECT IF(MAX(%s) IS NULL ,1 , MAX(%s)+1) AS max_sort FROM %s', $sort_field, $sort_field, $table_name);
        $sort_array = $G_SHOP->DBCA->stmt_query($search_sql);

        //返回排序序号
        return $sort_array[0]->max_sort;
    } catch (Exception $e) {
        error_log($e->getMessage());
        return 0;
    }
}

/**
 * 查询城市信息
 * @return array|null
 */
function get_city() {

    global $G_SHOP;
    return $G_SHOP->getCache('city');                                        //读取缓存城市数据

}

/**
 * 查询配送站信息
 * @param null|int $cityID 城市ID
 * @return array
 */
function get_distribution( $cityID = null ) {

    $distribution_array = array(
        0 => array(
            'id' => 1,
            'name' => '松江配送站'
        ),
        1 => array(
            'id' => 2,
            'name' => '普陀配送站'
        )
    );

    return $distribution_array;
}

/**
 * 商品促销号
 *
 * @return unknown
 */
function promotion_seq_no(){

    global $G_SHOP;

    $G_SHOP->DBCA->stmt_query('UPDATE promotion_seqno SET seqno=LAST_INSERT_ID(seqno+1)');
    if ($r =& $G_SHOP->DBCA->stmt_query('SELECT LAST_INSERT_ID() seq_no')){
        $promotionID = $r[0]->seq_no;
        return $promotionID ;
    }

    return null ;
}

/**
 * 将商品详情描述的图片转化为延迟加载图片
 * @param string $description		商品详情描述
 * @param string $suffix			商品图片后缀
 * @return mixed
 */
function img_to_loadding_format( $description, $suffix = '' ) {

    preg_match_all ('/(<img )(.[^>]*)(>)/', $description , $matchArray);
    if(empty($matchArray))
        return $description ;

    //被截取的图片正则
    $picArray = $matchArray[0] ;

    if(!empty($picArray)){
        foreach ($picArray as &$p_l)  {
            //检查是否已经存在orginalsrc
            if(stripos( $p_l , 'orginalsrc') !== false)
                continue ;

            //将图片打散
            $imgArr  = explode(' ', $p_l) ;
            $imgPath = '' ;
            if($imgArr) {
                foreach ($imgArr as &$i_l) {
                    //将src 换成默认的图片路径
                    if(stripos( $i_l , 'src') !== false) {
                        $imgPath .= ' src="' . G_SHOP_CDN . '/shop/theme/xth2/images/comm/lazyloading.gif" ' ;

                        //得到图片路径
                        $srcArr1  = explode('"' , $i_l) ;
                        $srcArr2  = explode("'" , $i_l) ;

                        if(count($srcArr1) > 1)
                            $srcStr = $srcArr1[1] ;
                        else
                            $srcStr = $srcArr2[1] ;

                        if($suffix != '')
                            $imgPath .= sprintf(' orginalsrc="%s?%s" ' , $srcStr , $suffix) ;
                        else
                            $imgPath .= sprintf(' orginalsrc="%s" ', $srcStr);
                    }else
                        $imgPath .= ' ' . $i_l . ' ' ;
                }
            }

            //将图片重新放入到内容中
            $description = str_replace($p_l , $imgPath , $description) ;

        }
    }

    //返回最新的详情
    return $description ;

}

/**
 * 生成任意长度的随机字符串
 * @param int $len 长度
 * @param string $format 格式 mixed：混合 number：数字
 * @return string
 */
function get_random_string( $len, $format = 'mixed' ) {

    if ($format == 'number') {
        $chars = array(
            '0', '1', '2', '3', '5', '6', '7', '8', '9'
        );
    } else {
        $chars = array(
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
            'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
            'w', 'x', 'y', 'z', '0', '1', '2', '3', '5', '6', '7',
            '8', '9'
        );
    }

    $charsLen = count($chars) - 1;
    shuffle($chars);    // 将数组打乱

    $output = '';
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }

    return $output;

}

/**
 * 获得星期
 * @return array
 */
function get_week() {

    $week = date('w');
    return array(
        'zh' => $GLOBALS['zh_week'][$week], //中文
        'en' => $GLOBALS['en_week'][$week],  //英文
        //add by allen.qiang 20141027--start
        'fr' => $GLOBALS['fr_week'][$week],  //法文
    );

}

/**
 * 分页程序
 * @author 刘道健
 * @param int $pageIndex 当前页码
 * @param int $count 总数量
 * @param int $displayCount 每页显示数量
 * @param string $link 分页链接，链接里的页码部分用%d代替，在本方法中会用sprintf函数替换%d为页码。例：/shop/member_order.php?pageIndex=%d
 * @param object $smarty smarty对象实例
 * @param string $tpl 模板文件
 * @return null：总页小于等于1，不用分页
 * 		   $pageHtml：分页HTML代码，在前台直接使用就可以
 */
function shop_page( $pageIndex, $count, $displayCount, $link, &$smarty, $tpl = 'page.tpl' ) {

    $pageCount = ceil($count / $displayCount);
    if ($pageCount == 1)
        return '';

    $pageLinks = array();
    if ($pageIndex > 1) {
        $pageLinks['goto_previous_page_link'] = sprintf($link, $pageIndex - 1);
    }
    if ($pageIndex < $pageCount) {
        $pageLinks['goto_next_page_link'] = sprintf($link, $pageIndex + 1);
    }
    $i = 1;
    while ($i <= $pageCount) {
        $pageLinks['link'][] = array('href' => sprintf($link, $i), 'text'=> $i);
        if ($pageIndex - 3 > $i) {
            $pageLinks['link'][] = array('href' => '', 'text'=> '...');
            $i = $pageIndex - 3;
        } else if ($i < $pageCount && $pageIndex + 3 < $i && $pageCount - 1 > $i) {
            $pageLinks['link'][] = array('href'=>'', 'text'=>'...');
            $i = $pageCount - 1;
        }
        $i++;
    }

    $pageLinks['pageIndex'] = $pageIndex;
    $pageLinks['total'] = $count;
    $pageLinks['pageCount'] = $pageCount;
    $smarty->assign_by_ref('pageLinks', $pageLinks);
    $pageHtml = $smarty->fetch($tpl);
    return $pageHtml;

}

/**
 * 活动地址的经纬度
 * @param string $address 地址
 * @return array
 * 已有地图服务种类
 * BAIDU,G7,QQ
 */
function get_address_coordinate( $address ) {

    $coordinate_array = array(
        'longitude' => null,
        'latitude' => null,
        'precise' => 0,
        'match' => 0,
        'locator' => null
    );

    $address = str_replace(' ', '', $address);
    $G_LATITUDE_ARRAY=explode(',',G_LATITUDE_ARRAY);                                //截取地址经纬度匹配规则名称
    foreach($G_LATITUDE_ARRAY as $index => $latitude){
        //统一转大写
        $latitude = strtoupper($latitude);
        if($latitude=="BAIDU"){                                                      //地址经纬度匹配规则-百度
            quanli_require('framework/Maps/mapBAIDU.php');
            $mapBAIDU = new mapBAIDU();
            $coordinate_array =$mapBAIDU->getGeoAddress($address,$index);
            if( $coordinate_array['flg'] == 1)
                break;
        }else if($latitude=="G7"){                                                  //地址经纬度匹配规则-G7
            quanli_require('framework/G7/G7Base.php');
            $get_g7map= new G7Base();                                                //调用G7地址库类
            $g7_data = $get_g7map->getGeoAddress($address);                          //根据地址获得G7地址库的经纬度
            if($g7_data['ilevel']>=10){                                            //G7地址库返回精准度等级
                $coordinate_array['longitude'] = $g7_data['lng'];
                $coordinate_array['latitude'] =  $g7_data['lat'];
                $coordinate_array['precise'] = 1;
                $coordinate_array['match'] = 1;
                break;
            }else if($index==0){                                                    //默认G7经纬度
                $coordinate_array['longitude'] = $g7_data['lng'];
                $coordinate_array['latitude'] = $g7_data['lat'];
                $coordinate_array['precise'] = 0;
                $coordinate_array['match'] = 1;
            }
        }else if($latitude=="QQ") { //地址经纬度匹配规则-QQ
            quanli_require('framework/Maps/mapQQ.php');
            $mapQQ = new mapQQ();
            $coordinate_array =$mapQQ->getGeoAddress($address,$index);
            if( $coordinate_array['flg'] == 1)
                break;
        }else if($latitude=="GD") { //地址经纬度匹配规则-高德
            quanli_require('framework/Maps/mapGD.php');
            $mapGD =  new mapGD();
            $coordinate_array = $mapGD->getGeoAddress($address,$index);
            if( $coordinate_array['flg'] == 1)
                break;
        }
    }
    return $coordinate_array;

}

/**
 * @param $gg_lon
 * @param $gg_lat
 * @return mixed
 * 火星系地址坐标-->百度坐标
 */
function bd_encrypt($gg_lon,$gg_lat)
{
    $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    $x = $gg_lon;
    $y = $gg_lat;
    $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
    $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
    $data['lng'] = $z * cos($theta) + 0.0065;
    $data['lat'] = $z * sin($theta) + 0.006;
    return $data;
}

/**
 * 获得地图区域
 * @param double $longitude 经度
 * @param double $latitude 纬度
 * @param int $cityID 城市ID
 * @param int $type 1、配送站 2、运费
 * @return null|array
 */
function get_map_area( $longitude, $latitude, $cityID, $type ) {

    quanli_include('module/base/system/mapAreaZoning.class.php');
    quanli_include('module/base/common/quanliPointLocation.class.php');

    //实例地图区域类
    $mapAreaZoning = new mapAreaZoning( );

    $quanliPointLocation = new quanliPointLocation();


    //查询城市下的所有地图区域
    $arg_array = array(
        'cityID' => $cityID,
        'type' => $type,
        'useFlg' => 1,
        'brandID' => G_BRANDID_DEFAULT
    );
    $map_area_array = $mapAreaZoning->searchMapArea( $arg_array );
    if(!$map_area_array){
        return null;
    }

    $result_array = array(
        'areaID' => 0,
        'default_areaID' => 0
    );

    //城市经纬度
    $lgtLat = $longitude . ',' . $latitude;

    foreach($map_area_array as $area) {

        if (empty($result_array['default_areaID'])) {
            $result_array['default_areaID'] = $area['areaID'];
        }

        //经纬度集合
        $lgtLat_array = array();
        $map_area_detail_array = $mapAreaZoning->searchMapAreaPath( $area['areaID'] );
        foreach($map_area_detail_array as $area_detail){
            $lgtLat_array[] = $area_detail['longitude'].','.$area_detail['latitude'];
        }

        //通函数筛选出匹配的经纬度区域  匹配到返回区域ID  否则返回false
        $filter_result = $quanliPointLocation->polygon($lgtLat, $lgtLat_array);
        if(!$filter_result){
            continue;
        }
        if($result_array['areaID'] == 0){
            $result_array['areaID'] = $area['areaID'];
            break;
        }
    }
    return $result_array;
}

/**
 * 获取客户端ip地址
 * @return string
 */
function get_ip() {
    if ( getenv( "HTTP_REMOTEIP" ) && strcasecmp( getenv( "HTTP_REMOTEIP" ), "unknown" ) ) {
        $ip = getenv( "HTTP_REMOTEIP" );
    } else if ( getenv( "HTTP_CLIENT_IP" ) && strcasecmp( getenv( "HTTP_CLIENT_IP" ), "unknown" ) ) {
        $ip = getenv( "HTTP_CLIENT_IP" );
    } else if ( getenv( "HTTP_X_FORWARDED_FOR" ) && strcasecmp( getenv( "HTTP_X_FORWARDED_FOR" ), "unknown" ) ) {
        $ip = getenv( "HTTP_X_FORWARDED_FOR" );
    } else if (getenv( "REMOTE_ADDR" ) && strcasecmp( getenv( "REMOTE_ADDR" ), "unknown" ) ) {
        $ip = getenv( "REMOTE_ADDR" );
    } else if ( isset( $_SERVER[ 'REMOTE_ADDR' ] ) && $_SERVER[ 'REMOTE_ADDR' ]
        && strcasecmp( $_SERVER[ 'REMOTE_ADDR' ], "unknown" ) ) {
        $ip = $_SERVER[ 'REMOTE_ADDR' ];
    } else {
        $ip = "unknown";
    }
    if ( strpos( $ip, ',' ) ){
        $ipArr = explode( ',', $ip );
        $ip = $ipArr[ 0 ];
    }
    return( $ip );
}

/**
 * 解析URL参数格式的字符串
 * @param string $text 字符串
 * @return array
 */

function parseUrlParams( $text ) {

    $parse_array = explode('&', urldecode($text));
    $data_array = array();

    if ($parse_array) {
        foreach($parse_array as &$item) {
            //获得第一个=字符的位置
            $nPos = strpos($item, '=');
            //获得字符串长度
            $nLen = strlen($item);
            //获得变量名
            $key = substr($item, 0, $nPos);
            //获得数值
            $value = substr($item, $nPos+1, $nLen-$nPos-1);
            //放入数组中
            $data_array[$key] = $value;
        }
    }
    return $data_array;
}

/**
 * 加载静态页面文件
 * @param mix $paras
 * @return string
 * @creator allen.qiang 2015-06-03
 */

function loadScript($paras) {

    extract($paras);//从数组中把变量导入到当前的符号表中

    //$type 类型：js、css 目前只有这两种
    //$path 路径 index、cart、checkout...
    //$file 文件名 xxx.js、xxx.css...可以一个也可以多个用[,]隔开
    //$framework 是否类库下的文件 n、y
    //G_THEME_ROOT 前台模板文件目录 例：D:/inonesoft/nginx/htdocs_mcake//shop/theme/xth1/
    //G_THEME_URL 前台模板文件目录 例：http://xxx.xxxx.com/shop/theme/xth1/
    //G_SHOP_CDN 网址 例：http://xxx.xxx.com
    //G_APPLICATION_BASEPATH 根目录 例：D:/inonesoft/nginx/htdocs_mcake/

    if(!isset($type,$file) || empty($type) || empty($file))
        return '';

    $html = '';

    switch($type){

        case 'js':

            $tag = '<script type="text/javascript" src="?"></script>';

            break;

        default:

            $tag = '<link rel="stylesheet" type="text/css" href="?" />';

            break;
    }

    $files = explode(',',$file);

    $path = isset($path) && !empty($path) ? $path.'/' : '';

    if(!isset($framework) || $framework=='n'){

        foreach($files as $filename){

            $file_path = G_THEME_ROOT.$type.'/'.$path.$filename;

            if(is_file($file_path)){

                $url = G_THEME_URL.$type.'/'.$path.$filename.'?v='.filemtime($file_path);

                $html .= str_replace('?',$url,$tag);
                $html .= "\n";

            }
        }

    }

    if(isset($framework) && $framework=='y' && isset($path) && !empty($path)){

        $path = '/'.$path;

        foreach($files as $filename){

            $file_path = G_APPLICATION_BASEPATH.$path.$filename;

            if(is_file($file_path)){

                $url = G_SHOP_CDN.$path.$filename.'?v='.filemtime($file_path);
                
                $html .= str_replace('?',$url,$tag);
                $html .= "\n";

            }
        }
    }

    return $html;

}

/**
 * 从基本设置中取得巧克力牌图片URL
 */
function getChocolateChipImg(){
    global $G_SHOP;

    $bday_img = '';
    $bday_array = $G_SHOP->DBCA->stmt_query('SELECT itemName FROM sys_item WHERE itemCategoryID = 33 AND useFlg = 1');
    if($bday_array){
        $bday_img = $bday_array[0]->itemName;
    }
    return $bday_img;
}

/**
 * 从配件数据中取得生日蜡烛图URL
 */
function getBdCandleImg(){
    global $G_SHOP;

    $bday_candle_img = '';
    $goods_fittings_img = $G_SHOP->DBCA->stmt_query('SELECT image FROM goods_fittings WHERE fitID = 53');
    if($goods_fittings_img) {
        $bday_candle_img = $goods_fittings_img[0]->image;
    }
    return $bday_candle_img;
}

/**
 * 取得发票内容
 */
function getInvoiceContent(){
    $itemHandler = new itemHandler();
    $item_array = array(
        'itemCategoryID' => 12,
        'useFlg' => 1
    );
    return  $itemHandler->searchItem( $item_array );
}

/**
 * 取得商品标签
 */
function getTagData(){
    global $G_SHOP;
    $sql = 'SELECT T_g_t.*,gt.memoName FROM (
            SELECT tagGroupID,tagGroupName,tagID,tagName FROM goods_tag_relation GROUP BY tagGroupID,tagID
            ) AS T_g_t  INNER JOIN goods_tag gt ON gt.tagID = T_g_t.tagID ORDER BY sortOrder ASC';
    $goods_tag_array = $G_SHOP->DBCA->stmt_query($sql);

    $tag_group_array = array();
    if ($goods_tag_array) {
        foreach($goods_tag_array as &$tag) {
            if (!isset($tag_group_array[$tag->tagGroupID])) {
                $tag_group_array[$tag->tagGroupID] = array(
                    'name' => $tag->tagGroupName,
                    'tag' => array()
                );
            }
            $tag_group_array[$tag->tagGroupID]['tag'][] = array(
                'name' => $tag->tagName,
                'value' => $tag->memoName,
                'id' => $tag->tagID,
            );
        }
    }
    return $tag_group_array;
}

/**
 * 取得WAP意见反馈参数
 */
function getWapFedBack(){
    //实例化字典类
    $itemHandler = new itemHandler();

    //取得wap意见反馈参数
    $itemStart_array = array(
        'useFlg' => 1,
        'sortname' => 'itemID',
        'sortorder' => 'ASC',
        'itemCategoryID' => 35
    );

    //查询字典表信息
    return $itemHandler->searchItem( $itemStart_array );
}

/**
 * 取得单个商品所有价格中最低的数据。
 */
function getGoodsMiniPrice($mainPostID){
    if(G_AD_ALLIANCE){
        global $G_SHOP;
        //查询在售商品的最小磅数价格 cps、dsp推送使用
        $search_goods_sql = 'SELECT salePrice FROM goods_sale WHERE mainPostID = ? AND useFlg = 1 ORDER BY salePrice ASC LIMIT 1';
        $goods_info = $G_SHOP->DBCA->stmt_query($search_goods_sql,'i',$mainPostID);
        return  $goods_info[0]->salePrice;
    }
    return 0;
}

/**
 * 取得商品图片
 */
function getGoodsPics($twoPostID){
    global $G_SHOP;
    //实例商品类
    $quanliGoods = new quanliGoods( $G_SHOP->DBCA );

    $goods_picture_array = $quanliGoods->searchGoodsPicture( $twoPostID );
    $goodsPic = array();
    if ($goods_picture_array) {
        foreach ($goods_picture_array as &$pic_list) {
            $goodsPic[] = array (
                'big_link' => str_replace('list_', 'big_', $pic_list['pictureLink']),
                'middle_link' => str_replace('list_', 'middle_', $pic_list['pictureLink']),
                'small_link' => str_replace('list_', 'small_', $pic_list['pictureLink'])
            );
        }
    }
    return $goodsPic;
}

/**
 * 取得会员VIP等级
 */
function getCustVipLevel($rankName){
    $vipLevel = '';
    switch($rankName){
        case 'level 1':
            $vipLevel = 'vip1';
            break;
        case 'level 2':
            $vipLevel = 'vip2';
            break;
        case 'level 3':
            $vipLevel = 'vip3';
            break;
        case 'level 4':
            $vipLevel = 'vip4';
            break;
        case 'level 5':
            $vipLevel = 'vip5';
            break;
        default:
            $vipLevel = 'vip1';
            break;
    }
    return $vipLevel;
}


/**
 * 重写error_log 无参数时自动记录日志索引
 * 若要输出SQL 请在SQL方法执行前调用 elog('psql');
 * @param $obj   输出内容 或 null
 * @param $path 'D:/test.log' 或 null
 */
function elog ($obj = null, $path = null)
{
    if(is_array($obj) || is_object($obj))
        $obj = print_r($obj,1);
    elseif($obj === null) {
        if(!isset($GLOBALS["logIndex"])) $GLOBALS["logIndex"] = 1;
        $obj = 'LOG--------------- '.$GLOBALS["logIndex"];
        $GLOBALS["logIndex"]++;
    }
    $path ? error_log($obj, 3, $path) : error_log($obj);
}